package com.end;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

public class Server {
    Socket socket;

    Server() throws Exception{
        ServerSocket serverSocket = new ServerSocket(6666);
        socket = serverSocket.accept();
        System.out.println("登录成功");
    }
    public static void main(String[] args) throws Exception{

            Server server = new Server();
            DataInputStream dataInputStream = new DataInputStream(server.socket.getInputStream());
            while(true){
                String[] all = dataInputStream.readUTF().split("\\|");
                boolean flag;
                try{
                    if(all[0].equals("登录")){
                        flag = server.login(all);
                    }else{
                        flag = server.zhuce(all);
                    }
                    DataOutputStream dataOutputStream = new DataOutputStream(server.socket.getOutputStream());
                    if(flag){
                        dataOutputStream.writeUTF("true");
                    }else{
                        dataOutputStream.writeUTF("false");
                    }
                }catch (Exception e){
                    System.out.println(e.getCause());
                }
            }



    }
    public boolean zhuce(String[] all) throws Exception{
        Properties properties = new Properties();
        Reader reader = new FileReader("user.properties");
        properties.load(reader);

        if(properties.stringPropertyNames().contains(all[1])){
            return false;
        }else{
            properties.setProperty(all[1], all[2]);
            try (FileOutputStream fos = new FileOutputStream("user.properties")) {
                properties.store(fos, "User accounts");
            }

            return true;
        }
    }
    public boolean login(String[] all) throws Exception{

        Properties properties = new Properties();
        Reader reader = new FileReader("user.properties");
        properties.load(reader);
        if(properties.stringPropertyNames().contains(all[1])){
            if(properties.getProperty(all[1]).equals(all[2])){
                return true;
            }else return false;
        }else{
            return false;
        }
    }
}
